package com.yhsimon.controller;

import com.yhsimon.entity.*;
import com.yhsimon.feign.CommodityFeign;
import com.yhsimon.feign.OrderFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/order")
public class OrderHandler {

    @Value(value = "${server.port}")
    private String port;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private CommodityFeign commodityFeign;

    @GetMapping("/index")
    @ResponseBody
    public String index() {
        return this.port;
    }

    @GetMapping("/findAllByUId")
    @ResponseBody
    public OrderVO findAllByUId(@RequestParam("page") int page, @RequestParam("limit") int limit, HttpSession session) {
        int index = (page - 1) * limit;
        User user = (User) session.getAttribute("user");
        System.out.println(user.getId());
        OrderVO orderVO = orderFeign.findAllByUId(user.getId(), index, limit);
        return orderVO;
    }

    @GetMapping("/findAllByState")
    @ResponseBody
    public OrderVO findAllByState(@RequestParam("page") int page, @RequestParam("limit") int limit) {
        OrderVO orderVO = orderFeign.findAllByState((page - 1) * limit, limit);
        return orderVO;
    }

    @GetMapping("/findAll")
    @ResponseBody
    public OrderVO findAll(@RequestParam("page") int page,@RequestParam("limit") int limit){
        return orderFeign.findAll((page-1)*limit,limit);
    }

    @GetMapping("/redirect/{location}")
    public String index1(@PathVariable("location") String location) {
        return location;
    }

    @GetMapping("/updateState/{id}/{state}")
    public String updateState(@PathVariable("id") int id, @PathVariable("state") int state, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        System.out.println("order的id:"+id);
        orderFeign.updateState(id, state, admin.getId());
        return "order_handler";
    }

    @GetMapping("/save/{id}")
    public String save(@PathVariable("id") int id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Commodity commodity = commodityFeign.findById(id);
        commodity.setCount(commodity.getCount()-1);
        commodityFeign.update(commodity);
        Order order = new Order();
        order.setCommodity(commodity);
        order.setUser(user);
        order.setDate(new Date());
        System.out.println(order);
        orderFeign.save(order);
        return "redirect:/account/redirect/order";
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") int id) {
        orderFeign.deleteById(id);
        return "redirect:/account/redirect/order";
    }
}
